﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 电能表帧命令校验码生成工具
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();            
            txtAddr.Text = "00 00 00 00 00 00";
            txtBiaoShiFu.Text = "00 00 FF 00";
            txtCtl.Text = "11 ";
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            string padr = txtAddr.Text;
            string pctl = txtCtl.Text; //控制码
            string pbs = txtBiaoShiFu.Text;//标识符
            pbs = AddCodeThree(pbs);
            string pdLen = (pbs.Length/2).ToString("00")+" ";//数据长度
            string pend = " 16 ";

            string sum = "68 " + padr + " 68 " + pctl + pdLen + pbs;

            int cs = GetSum(sum)%256;
            string pcs = " " + Convert.ToString(cs, 16);

            string all = sum + pcs + pend;
            MessageBox.Show("本次生成校验码为：" + pbs.ToUpper());

            txtOutput.Text = all.ToUpper();            
        }

        public string Revease3(string original)
        {
            int length = original.Length;
            StringBuilder sb = new StringBuilder(length);
            for (int i = length - 1; i >= 0; i -= 2)
            {
                sb.Append(original[i-1]);
                sb.Append(original[i]);
            }
            return sb.ToString();
        }

        public string AddCodeThree(string str)
        {
            str = str.Replace(" ", "");
            string tmp = null;
            int tem = 0;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < str.Length; i+=2)
            {
                tmp = str.Substring(i, 2);
                tem = (tmp == "FF") ? (-1 + 51) : Convert.ToInt32(tmp, 16) + 51;
                sb.Append(Convert.ToString(tem, 16));                
            }
            return Revease3(sb.ToString());
        }
        public int GetSum(string str)
        {
            str = str.Replace(" ", "");
            string tmp = null;
            int Sum = 0;
            for (int i = 0; i < str.Length; i += 2)
            {
                tmp = str.Substring(i, 2);
                Sum += Convert.ToInt32(tmp, 16);
            }
            return Sum;
        }
    }
}
